$(document).ready(function () {
    var allshoppingFee = 0;
    var FeeType = 1;
    var allDiscountFee = 0;
    var itemTemplate2 = '<div class="my_cart" data-sku="{ProductSkuNo}">' +
                                	'<div class="input">' +
                                        '<label>' +
                                           ' <input type="checkbox" onchange="updateAll(\'update\');" sel="{ProductSkuNo}">' +
                                       ' </label>' +
                                   ' </div>' +
                                    '<div class="left"><img src="{ThumbnailImg}"></div>' +
                                    '<div class="center">' +
                                       ' <h2>{ProductName}{SkuHtml}</h2>' +
                                       ' <p>单价：<span>￥{SalePrice}</span></p>' +
                                        '<div class="cart_num">' +
                                            '<div class="num">' +
    //                    	'<div class="n1">数量</div>' +
                                                '<div class="n2"><a href="#" id="min1" onclick="increaseNumber(-1,\'{ProductSkuNo}\')">-</a><input UnitPrice="{SalePrice}"  type="text" value="{Counter}" name="{ProductSkuNo}" id="text_box1" onblur="setNumber(\'{ProductSkuNo}\')" /><a href="#" id="add1" onclick="increaseNumber(1,\'{ProductSkuNo}\')">+</a></div>' +
                                            '</div>' +
                                        '</div>' +
                                   ' </div>' +
                                   ' <div class="right"><a href="ProductDetail.aspx?no={ProductNo}" data-ajax="false"><img src="images/usercenter_righticon.png"></a></div>' +
                                    '<div class="clear"></div>' +
                               ' </div>';
    var itemTemplate = '<div class="promotionGroup "{dis}><div class="givePresent" data-pk="{PkType}" data-type="{Type}" {Display}>' +
                 '<div style="width:100%;display: flex;align-items: center;justify-content: space-between;"> <span class="give {ActiveClass}" {Style}>优惠</span>' +
                   '<div class="man" {ShippStyle}><span class="man_satisfy" data-type="{Type}">{satisfy}<span class="man_bord {dom}" {Style}> ({SatisfyType})</span></span></div>' +
                  '<div style="float:right"><a href="{RuleUrl}" data-ajax="false" class="merge">拼优惠</a></div></div><div class="addfee"><p>{Content}</p></div></div>{List}</div>'; //项模板
    var handler = $('.listviewHandler').listviewHandler();
    handler.initialize({
        loaderBtn: $('#moreBtn'), //加载数据按钮（点击加载下一页）
        emptyHtml: '<div class="my_cart" style="height: 20px;"><div class="center"> 无记录</div></div>', //无记录时显示此htm
        itemTemplate: '<div class="promotionGroup"><div class="givePresent" data-pk="{PkType}" data-type="{Type}" {Display}>' +
                ' <span class="give {ActiveClass}" {Style}>优惠</span>' +
                   '<div class="man" {ShippStyle}>{satisfy}<span class="man_bord {dom}" {Style}> ({SatisfyType})</span></div>' +
                  '<div style="float:right"><a href="{RuleUrl}" data-ajax="false" class="merge">拼优惠</a></div></div>{List}</div>', //项模板
        pageIndex: 1, //页码（从1起算）
        pageSize: 20, //页大小
        totalCount: 999, //总记录数
        itemHandler: function (data, itemTemplate, container) {//数据各项处理
        },
        beforeHandleResult: function (result, totalCount, container) {



            if (totalCount > 0) {
                $('.cart_delete').show();
            }
            //筛选RelationCode
            var PromotionHash = {};
            SplitRelationCode(result, PromotionHash);
            var htmlObj = "";
            //排序规则
            var sortProp = [];
            for (var prop in PromotionHash) {
                sortProp.push(prop);
            }
            sortProp = sortProp.sort();
            sortProp = sortProp.reverse();
            //拿到筛选排序后的规则 进行遍历
            $(sortProp).each(function () {
                var prop = this;
                $(PromotionHash[prop]).each(function () {
                    var listobj = this;
                    listobj.Display = "style='display:none'";
                    listobj.Style = ""; //不是运费就显示
                    listobj.ShippStyle = '';
                    listobj.ActiveClass = "";
                    listobj.dom = "noMan";
                    listobj.dis = "";
                    listobj.List = "";
                    //每条规则所包含的产品
                    $(listobj.ProductList).each(function () {
                        var skuHtml = '';
                        var skuData = $.parseJSON(this.SkuParamCode);
                        $(skuData).each(function () { skuHtml += '<span>【' + this.ItemName + '】</span>'; });
                        this.SkuHtml = skuHtml;
                        this.ThumbnailImg = firstThumbnail(this.ThumbnailImg)
                        listobj.List += itemTemplate2.format(this);
                    })
                    var satisfy = "";
                    var PkType = "";
                    var SatisfyType = "";


                    if (listobj.RelationCode != 0) {
                        PkType = listobj.DeptCode + listobj.RelationCode;
                        listobj.PkType = PkType;
                    } else {
                        PkType = listobj.DeptCode + listobj.RuleId;
                        listobj.PkType = PkType;
                    }
                    //规则循序,处理优惠显示:
                    //赠品
                    if (listobj.GiftList && listobj.GiftList.length > 0 && listobj.Type == 0) {
                        satisfy = listobj.Memo;
                    }
                    //折扣
                    if (listobj.DiscountFee > 0 && listobj.Type == 0) {
                        satisfy = listobj.Memo;
                    }
                    //运费
                    if (listobj.Type == 1) {
                        satisfy = listobj.Memo;
                    }
                    listobj.satisfy = satisfy;

                    if (listobj.Status != -9) {//表示产品没参与任何优惠
                        listobj.Display = "";
                    }
                    //优惠,优惠金额的显示处理:
                    //邮费收取(初始化)
                    if (listobj.Type == 1 && listobj.Status == 1) {
                        allshoppingFee += listobj.ShippingFee;
                        FeeType = 2;
                        $(".man .noMan").html('');
                    }
                    //不收取邮费
                    if (listobj.Type == 1 && listobj.Status != 1) {
                        listobj.ActiveClass = "active";
                        $(".man .noMan").html('');
                    }
                    //普通优惠的优惠总额
                    if (listobj.Type == 0 && listobj.Status == 1) {
                        listobj.ActiveClass = "active";
                        listobj.dom = "";
                        SatisfyType = '已满足';
                        listobj.SatisfyType = SatisfyType;
                        allDiscountFee += listobj.DiscountFee;
                    }
                    if (listobj.Type == 0 && listobj.Status != 1) {
                        SatisfyType = '未满足';
                        listobj.SatisfyType = SatisfyType;
                    }

                    htmlObj += itemTemplate.format(listobj);
                });
            });

            var $el = $('<div></div>').append(htmlObj);


            (function () {
                var postage_tmp = {};
                var promotionList = result.DiscountResult.PromotionList;
                $.each(promotionList, function (index, rule) {
                    if (rule.Type === 1) {
                        var pkType = '';
                        if (rule.RelationCode != 0) {
                            pkType = rule.DeptCode + rule.RelationCode;
                        } else {
                            pkType = rule.DeptCode + rule.RuleId;
                        }
                        rule.pkType = pkType;

                        $.each(rule.ProductList, function (index, product) {
                            var is = promotionList.some(function (rule) {
                                return rule.Type !== 1 && rule.Type !== null && rule.ProductList.some(function (item) {
                                    return item.ProductNo === product.ProductNo;
                                });
                            });
                            if (is) {
                                var elstring = '[data-pk="' + pkType + '"][data-type="1"]';
                                $el.find(elstring).parent().find('.my_cart[data-sku="'+product.ProductSkuNo+'"]').remove();
                                postage_tmp[product.ProductNo] = elstring;
                            }
                        });
                    }
                });
                $.each(promotionList, function (index, rule) {
                    if (rule.Type === 3) {
                        var pkType = '';
                        if (rule.RelationCode != 0) {
                            pkType = rule.DeptCode + rule.RelationCode;
                        } else {
                            pkType = rule.DeptCode + rule.RuleId;
                        }
                        rule.pkType = pkType;

                        $.each(rule.ProductList, function (index, product) {
                            var is = promotionList.some(function (rule) {
                                return rule.Type !== 3 && rule.Type !== null && rule.ProductList.some(function (item) {
                                    return item.ProductNo === product.ProductNo;
                                });
                            });
                            if (is) {
                                var elstring = '[data-pk="' + pkType + '"][data-type="3"]';
                                $el.find(elstring).parent().find('.my_cart[data-sku="'+product.ProductSkuNo+'"]').remove();
                                postage_tmp[product.ProductNo] = elstring;
                            }
                        });
                    }
                });
                $.each(postage_tmp, function(productNo, elstring) {
                    var $elpk = $el.find(elstring).parent();
                    if (!$elpk.find('.my_cart').length) {
                        $elpk.remove();
                    }
                });
                $el = $el.children()
            })();


            $(".listviewHandler").append($el);
            var TotalProductPrice = result.TotalProductPrice;






            AllTotal(TotalProductPrice, allDiscountFee, allshoppingFee, FeeType);
        },
        afterHandleResult: function (result, totalCount, container) {
            $(result.DiscountResult.PromotionList).each(function () {
                var RelationCodePk = this.DeptCode + this.RelationCode; //当返回RelationCode!=0的时候用此datapk
                var RuleIdPk = this.DeptCode + this.RuleId; //当返回RelationCode==0的时候用此datapk
                if (this.RelationCode != 0) {
                    var obj = $(".listviewHandler [data-pk='" + RelationCodePk + "']").find(".give"); //根据返回过来的组合去修改对应的状态
                    var objNo = $(".listviewHandler [data-pk='" + RelationCodePk + "']").find(".man_bord");
                    var objsatisfy = $(".listviewHandler [data-pk='" + RelationCodePk + "']").find(".man_satisfy");
                    var objgivePresent = $(".givePresent[data-pk='" + RelationCodePk + "']");
                } else {
                    var obj = $(".listviewHandler [data-pk='" + RuleIdPk + "']").find(".give"); //根据返回过来的组合去修改对应的状态
                    var objNo = $(".listviewHandler [data-pk='" + RuleIdPk + "']").find(".man_bord");
                    var objsatisfy = $(".listviewHandler [data-pk='" + RuleIdPk + "']").find(".man_satisfy");
                    var objgivePresent = $(".givePresent[data-pk='" + RuleIdPk + "']");
                };
                if (this.Content == '' || this.Content === null) {
                    $(".listviewHandler [data-pk='" + RuleIdPk + "']").find(".addfee").hide();
                    $(".listviewHandler [data-pk='" + RelationCodePk + "']").find(".addfee").hide();
                }
                if (this.Type == 0 && this.Status == 1) {
                    obj.data('solid_obj', 1);
                };
                if (this.Type == 1 && obj.data('solid_obj') != 1) {
                    obj.hide();
                    objNo.hide();
                    objsatisfy.css({ 'margin-left': '10px' });
                };
            });
            if (totalCount == 0) {
                location.href = "EmptyShoppingCart.aspx";
                return;
            }
            //$(".man .noMan").html("未满足:");
            isShow((result.TotalProductPrice - allDiscountFee).toFixed(2));
            $('.listviewHandler').trigger('create');
            $('#selAll').prop("checked", true).checkboxradio("refresh");
            $('input[sel]').prop('checked', true).checkboxradio('refresh')
            // $('#selAll').trigger('change');
            LoadProduct(result, result.TotalProductPrice);





        },
        command: 'Member.LoadPromotionList',
        parameter: { Kind: 'shop' }
    });
    handler.nextPage();
});
/*当总价钱大于3000*/
function isShow(price) {
    if (price >= 3000) {
        $(".big_header").show();
        // $(".cartbtn").addClass("carbtnNo");
        // $(".cartbtn").attr("onclick", "");
    } else {
        $(".big_header").hide();
        // $(".cartbtn").removeClass("carbtnNo");
        // $(".cartbtn").attr("onclick", "submitOrder($(this));");
    }
}

function setCartbtnDisabled (errInfo) {
    if (!errInfo) {
        $(".cartbtn").data("disabled", false);
        $(".cartbtn").data("disabledText", '');
    } else {
        $(".cartbtn").data("disabled", true);
        $(".cartbtn").data("disabledText", errInfo);
    }
}

function increaseNumber(factor, sku) {
    var currentVal = parseInt($("input[name=" + sku + "]").val()) + factor;
    $("input[name=" + sku + "]").val(currentVal);
    setNumber(sku);
}

function setNumber(sku) {
    var currentVal = parseInt($("input[name=" + sku + "]").val());
    if (isNaN(currentVal)) currentVal = 1;
    if (currentVal < 1) currentVal = 1;
    if (currentVal > 99) currentVal = 99;
    $("input[name=" + sku + "]").val(currentVal);
    $("input[name=" + sku + "]").executeCommand({
        successCallBack: function (result) {
            //$('#totalPrice').text(result.TotalProductPrice);
            //$('#totalCount').text(result.TotalProductCount);
            updateAll("update");
        }
    }, 'Member.SelectProduct', { ProductList: [{ ProductSkuCode: sku, Counter: currentVal, Increment: 0}] });

}

//同步全选按钮
function updateAll(type) {
    var FeeType = 1;
    var check = true;
    var totalPrice = 0;
    var skuList = [];
    var reDiscountFee = 0;
    var allshoppingFee = 0;
    //拿到被选中的产品总价及skuno
    $('input[sel]').each(function () {
        if ($(this).prop('checked') == false) { 
            check = false;
        } else {
            var cntInput = $("[UnitPrice]", $(this).parents("div.my_cart"));
            totalPrice += parseInt(cntInput.val()) * cntInput.attr('UnitPrice');
            isShow(totalPrice);
            skuList.push($(this).attr("sel"));
        }
    });
    if (skuList.length > 0) {
        $('input[sel]').executeCommand({
            successCallBack: function (result) {
                $(".give").removeClass("active"); //初始样式
                $(".man_bord").text(" (未满足)");
                $(".man_satisfy[data-type='3']").css('color', '');
                LoadProduct(result, totalPrice);
                isShow(totalPrice.toFixed(2));
            }
        }, "Member.LoadPromotionList", { ProductSkuNo: skuList, Kind: "shop" })
    } else {
        $(".give").removeClass("active");
        $(".man_bord").text(" (未满足)");
        $('#selAll').prop("checked", check).checkboxradio("refresh");
        $('#totalPrice').text((totalPrice - reDiscountFee + allshoppingFee).toFixed(2));
        $("#totalZhe").text("(已优惠:￥0.00)"); //初始化优惠文本
        if (FeeType == '2' && ShippingFee != 0) {
            $("#totalZhe").text("(邮费:￥" + Math.abs(ShippingFee).toFixed(2) + ")");
        } else {
            $("#totalZhe").text("(已优惠:￥" + reDiscountFee.toFixed(2) + ")");
        }
        isShow(totalPrice.toFixed(2));
    }
}

//显示产品
function LoadProduct(result, totalPrice) {
    var FeeType = 1;
    var PromotionHash = {};
    var reDiscountFee = 0;
    var allshoppingFee = 0;
    var check = true;
    SplitRelationCode(result, PromotionHash);
    for (var prop in PromotionHash) {
        $(PromotionHash[prop]).each(function () {
            setCartbtnDisabled()
            var obj, objNo, objsatisfy, objgivePresent;
            var satisfy = '';
            var RelationCodePk = this.DeptCode + this.RelationCode; //当返回RelationCode!=0的时候用此datapk
            var RuleIdPk = this.DeptCode + this.RuleId; //当返回RelationCode==0的时候用此datapk
            if (this.RelationCode != 0) {
                obj = $(".listviewHandler [data-pk='" + RelationCodePk + "']").find(".give"); //根据返回过来的组合去修改对应的状态
                objNo = $(".listviewHandler [data-pk='" + RelationCodePk + "']").find(".man_bord");
                objsatisfy = $(".listviewHandler [data-pk='" + RelationCodePk + "']").find(".man_satisfy");
                objgivePresent = $(".givePresent[data-pk='" + RelationCodePk + "']");
            } else {
                obj = $(".listviewHandler [data-pk='" + RuleIdPk + "']").find(".give"); //根据返回过来的组合去修改对应的状态
                objNo = $(".listviewHandler [data-pk='" + RuleIdPk + "']").find(".man_bord");
                objsatisfy = $(".listviewHandler [data-pk='" + RuleIdPk + "']").find(".man_satisfy");
                objgivePresent = $(".givePresent[data-pk='" + RuleIdPk + "']");
            };
            //根据返回过来的组合去修改对应的状态
            //优惠的状态(点击加减后)
            if (this.Content == '' || this.Content === null) {
                $(".listviewHandler [data-pk='" + RuleIdPk + "']").find(".addfee").hide();
                $(".listviewHandler [data-pk='" + RelationCodePk + "']").find(".addfee").hide();
            } else {
                $(".listviewHandler [data-pk='" + RuleIdPk + "']").find(".addfee").children('p').html(this.Content).show();
                $(".listviewHandler [data-pk='" + RelationCodePk + "']").find(".addfee").children('p').html(this.Content).show();
            };
            if (this.Type == 0 && this.Status == 1) {
                if (this.GiftList && this.GiftList.length > 0) {
                    satisfy = this.Memo;
                    objsatisfy.html(satisfy + '<span class="man_bord noMan"> (已满足)</span>').css({ 'margin-left': '0px' });
                } else {
                    objsatisfy.html(this.Memo + '<span class="man_bord noMan"> (已满足)</span>').css({ 'margin-left': '0px' });
                }
                obj.show().addClass("active");
                reDiscountFee += this.DiscountFee;
            } else if (this.Status != 1 && this.Type == 0) {
                if (this.GiftList && this.GiftList.length > 0) {
                    satisfy = this.Memo;
                    objsatisfy.html(satisfy + '<span class="man_bord noMan"> (未满足)</span>').css({ 'margin-left': '0px' });
                } else {
                    objsatisfy.html(this.Memo + '<span class="man_bord noMan"> (未满足)</span>').css({ 'margin-left': '0px' });
                }
                obj.show().removeClass("active");
                objNo.text(" (未满足)");
            }
            //邮费的状态
            if (this.Status == 1 && this.Type == 1) {
                allshoppingFee += this.ShippingFee;
                FeeType = 2;
                obj.hide();
                objgivePresent.show();
                objsatisfy.css({ 'margin-left': '10px' });
            }
            if (this.Status != 1 && this.Type == 1) {
                objNo.text('');
                obj.hide();
                objsatisfy.css({ 'margin-left': '10px' });
            };

            if (this.Type == 3) {
                satisfy = this.Memo;
                obj.hide();
                if (this.Status == 1 && this.OrderUnable == false ) {
                    objsatisfy.html(satisfy + '<span class="man_bord noMan"> (已满足)</span>').css({ 'margin-left': '0px' });
                    objsatisfy.css('color', '');
                } else {
                    objsatisfy.html(satisfy + '<span class="man_bord noMan"> (未满足)</span>').css({ 'margin-left': '0px' });
                    objsatisfy.css('color', '#F9384D');
                    objNo.text(" (未满足)");
                    setCartbtnDisabled('含有未满足结算商品！');
                }
            }


            var promotionTitle = "";
            if (this.RelationCode != 0) {
                if (this.GiftList && this.GiftList.length > 0) {
                    promotionTitle = this.Memo;
                }
                //是否需要显示满足状态
                var showSatisfy = true;
                if (this.Type == 1) {
                    promotionTitle = this.Memo;
                    showSatisfy = false;
                }
                else if (this.Type == 0 && this.DiscountFee > 0) {
                    promotionTitle = this.Memo;
                }
                //if (this.ShippingFee > 0 && this.DiscountFee > 0) {
                //     giftlist += this.RuleTitle;
                //}
                if (promotionTitle) {
                    if (this.Status == 1) {
                        objsatisfy.html(promotionTitle + (showSatisfy ? '<span class="man_bord noMan"> (已满足)</span>' : '')).css({ 'margin-left': '10px' });
                    } else {
                        objsatisfy.html(promotionTitle + (showSatisfy ? '<span class="man_bord noMan"> (未满足)</span>' : '')).css({ 'margin-left': '10px' });
                    }
                }
            }
        });
    }; //End for (var prop in PromotionHash)
    $('#selAll').prop("checked", check).checkboxradio("refresh");
    $("#totalZhe").text("(已优惠:￥0.00)"); //初始化优惠文本
    var TotalProductPrice = result.TotalProductPrice
    AllTotal(TotalProductPrice, reDiscountFee, allshoppingFee, FeeType, totalPrice);
}

//总价的结算
function AllTotal(TotalProductPrice, allDiscountFee, allshoppingFee, FeeType, totalPrice) {
    if (totalPrice) {
        $('#totalPrice').text((totalPrice - allDiscountFee + allshoppingFee).toFixed(2));
    } else {
        $('#totalPrice').text((TotalProductPrice - allDiscountFee + allshoppingFee).toFixed(2));
    }
    if (FeeType == '2' && allDiscountFee == 0) {
        if (allshoppingFee != 0) {
            $("#totalZhe").text("(邮费:￥" + Math.abs(allshoppingFee).toFixed(2) + ")");
        } else {
            $("#totalZhe").text('');
        }
    };
    if (allDiscountFee > 0 && FeeType != '2') {
        $("#totalZhe").text("(已优惠:￥" + allDiscountFee.toFixed(2) + ")");
    };
    if (allDiscountFee > 0 && FeeType == '2') {
        if (allshoppingFee != 0) {
            $("#totalZhe").text("(邮费:￥" + Math.abs(allshoppingFee).toFixed(2) + ",已优惠:￥" + allDiscountFee.toFixed(2) + ")");
        } else {
            $("#totalZhe").text("(已优惠:￥" + allDiscountFee.toFixed(2) + ")");
        };
    };
};

//RelationCode!=0的问题
function SplitRelationCode(result, PromotionHash) {
    $(result.DiscountResult.PromotionList).each(function () {
        if (!PromotionHash[this.RelationCode]) {
            PromotionHash[this.RelationCode] = [];
        };
        if (PromotionHash[this.RelationCode]) {
            var tempR = {};
            tempR = this;
            if (this.RelationCode != 0) {
                if ((PromotionHash[this.RelationCode][0] && PromotionHash[this.RelationCode][0].Status != 1) || !PromotionHash[this.RelationCode][0]) {
                    PromotionHash[this.RelationCode][0] = tempR;
                } else if (this.Status == 1) {
                    PromotionHash[this.RelationCode][0] = tempR;
                }
            } else {
                PromotionHash[this.RelationCode].push(tempR);
            };
        };
    });
};

//删除产品
function removeProduct(ui) {
    confirmDialog('请确定要删除勾选的商品', function () {
        var skuList = [];
        $('input[sel]:checked').each(function () {
            skuList.push($(this).attr('sel'));
        });
        if (skuList.length == 0) {
            showTips("没有勾选的商品", 1500); return;
        }
        ui.executeCommand({
            successCallBack: function (result) {
                showTips('操作成功！', 500, function () { location.reload(); });
            }
        }, 'Member.RemoveProduct', { SkuCodeList: skuList });

    });
}

//提交订单
function submitOrder(ui) {
    if (ui.data('disabled')) {
        showTips(ui.data('disabledText'));
        return ;
    }
    var skuList = [];
    $('input[sel]:checked').each(function () {
        skuList.push($(this).attr('sel'));
    });
    if (skuList.length == 0) { showTips('请选择要结算的产品'); return; }
    ui.executeCommand({
        successCallBack: function (result) {
            location.href = 'SubmitOrder.aspx';
        }
    }, 'Member.ConfirmSelectProduct', { SkuCodeList: skuList });
}